package logic

import (
	"context"
	"fmt"
	"hippo/model/mysql"

	"hippo/hipporpc/hipporpc"
	"hippo/hipporpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type HippoAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHippoAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HippoAddLogic {
	return &HippoAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *HippoAddLogic) HippoAdd(in *hipporpc.HippoAddRequest) (*hipporpc.HippoAddResponse, error) {
	// todo: add your logic here and delete this line
	begin := mysql.DB.Debug().Begin()

	var class mysql.Class
	err := begin.Where("name = ?", in.ClassName).Find(&class).Error
	if err != nil {
		begin.Rollback()
		return nil, fmt.Errorf("查询数据失败")
	}
	begin.Where("id = ?", class.ID).Find(&class)

	if class.ID == 0 {
		class = mysql.Class{
			Name: in.ClassName,
		}
		err = begin.Create(&class).Error
		if err != nil {
			begin.Rollback()
			return nil, fmt.Errorf("分类数据添加失败")
		}
	}
	var hippo mysql.Hippo

	hippo = mysql.Hippo{
		Name:    in.Name,
		Price:   float64(in.Price),
		Image:   in.Image,
		ClassId: int64(class.ID),
	}
	err = begin.Create(&hippo).Error
	if err != nil {
		begin.Rollback()
		return nil, fmt.Errorf("添加数据失败")
	}
	if hippo.Name == in.Name {
		return nil, fmt.Errorf("商品名称已重复")
	}
	begin.Commit()
	return &hipporpc.HippoAddResponse{
		HippoId: int64(hippo.ID),
	}, nil
}
